package com.ruyuan2020.furnishing.tender.dao.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruyuan2020.common.exception.BusinessException;
import com.ruyuan2020.common.util.DateTimeUtils;
import com.ruyuan2020.furnishing.common.dao.impl.BaseDAOImpl;
import com.ruyuan2020.furnishing.tender.dao.BiddingDAO;
import com.ruyuan2020.furnishing.tender.domain.BiddingDO;
import com.ruyuan2020.furnishing.tender.mapper.BiddingMapper;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public class BiddingDAOImpl extends BaseDAOImpl<BiddingMapper, BiddingDO> implements BiddingDAO {

    @Override
    public Integer countBidding(Long tenderId) {
        LambdaQueryWrapper<BiddingDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BiddingDO::getTendererId, tenderId);
        return mapper.selectCount(queryWrapper);
    }

    @Override
    public Integer countBidding(Long tenderId, Long bidderId) {
        LambdaQueryWrapper<BiddingDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BiddingDO::getTenderId, tenderId);
        queryWrapper.eq(BiddingDO::getBidderId, bidderId);
        return mapper.selectCount(queryWrapper);
    }

    @Override
    public Long getTenderIdById(Long id) {
        LambdaQueryWrapper<BiddingDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(BiddingDO::getTenderId);
        queryWrapper.eq(BiddingDO::getId, id);
        return Optional.ofNullable(mapper.selectOne(queryWrapper)).map(BiddingDO::getTenderId).orElseThrow(() -> new BusinessException("投标信息不存在"));
    }

    @Override
    public void updateSigned(Long id) {
        LambdaUpdateWrapper<BiddingDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(BiddingDO::getSignedFlag, true);
        updateWrapper.set(BiddingDO::getSignedTime, DateTimeUtils.currentDateTime());
        updateWrapper.eq(BiddingDO::getId, id);
        mapper.update(null, updateWrapper);
    }
}
